package org.duoduo.common.redis.jedis3_1_0;

import com.duoduo.common.api.constants.Constant;
import com.duoduo.common.api.tuple.TwoTuple;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class RedisExecutor<T> {

    protected final static Logger log = LoggerFactory.getLogger(RedisExecutor.class);

    /**回调
     * @return 执行结果
     */
    public abstract T execute(String redisClusterType, Object jedis, String appName);

    /**
     * @return 执行结果
     */
    public T getResult(String key, String _appName) {
        T result = null;
        Object jedis = null;
        TwoTuple<String, RedisPool> redisPoolTuple = JedisCacheInit.getPoolAndAppName(key);
        if(redisPoolTuple == null) {
        	log.error("Redis execute exception：redisPoolTuple is null, key: " + key);
        }
        String appName = redisPoolTuple.first;
        RedisPool redisPool = redisPoolTuple.secord;
        try {
            jedis = redisPool.getResource();
            if(jedis == null){
            	log.error("get redis client fail from pool!");
            	return result;
            }
            if(_appName == null){
            	_appName = StringUtils.defaultString(appName, Constant.EMPTY_STRING);
            }
            result = execute(redisPool.getRedisClusterType(), jedis, _appName);
        } catch (Throwable e) {
        	log.error("Redis execute exception：" + e);
            return result;
        } finally {
        	redisPool.returnResource(jedis);
        }
        return result;
    }

}
